package com.sunshine_brid.ccras_server.service;

import cn.hutool.json.JSONObject;
import com.sunshine_brid.ccras_server.service.dao.EntityMenuMapper;
import com.sunshine_brid.ccras_server.service.entity.EntityMenu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.sunshine_brid.ccras_server.service.support.EntityMenuDynamicSqlSupport.*;
import static org.mybatis.dynamic.sql.SqlBuilder.isEqualTo;

/**
 * @author SunshineBrid
 */
@Service
public class EntityMenuMapperImpl {

    @Autowired
    EntityMenuMapper mapper;

    public JSONObject getEnityMenuMapperByProjectId(Integer id){

        List<EntityMenu> select = mapper.select(c->c.where(projectId,isEqualTo(id)));
        //创建项目
        JSONObject  project = new JSONObject();
        project.putOpt("id",id);
        project.putOpt("name",select.get(0).getProject());

        List<JSONObject> tierList=new ArrayList<>();

        Map<Integer,Integer> projectMap=new HashMap<>();
        List<Map<Integer,Integer>> tierMapList=new ArrayList<>();

        for(EntityMenu em:select){
            //创建层级
            Integer tierIndex = projectMap.get(em.getTierId());
            if(tierIndex==null){
                tierIndex=tierList.size();
                projectMap.put(em.getTierId(),tierIndex);
                JSONObject temp=new JSONObject();
                temp.putOpt("id",em.getTierId());
                temp.putOpt("name",em.getTier());
                temp.putOpt("entityList",new ArrayList<>());
                tierList.add(temp);
                tierMapList.add(new HashMap<>());
                project.putOpt("tierList",tierList);
            }
            //获取当前层级
            JSONObject tier=tierList.get(tierIndex);
            Map<Integer, Integer> tierMap=tierMapList.get(tierIndex);
            List<JSONObject> entityList= (List<JSONObject>) tier.get("entityList");
            //创建实体
            Integer entityIndex  = tierMap.get(em.getEntityId());
            if(entityIndex==null){
                entityIndex=entityList.size();
                tierMap.put(em.getEntityId(),entityIndex);
                JSONObject temp=new JSONObject();
                temp.putOpt("id",em.getEntityId());
                temp.putOpt("name",em.getEntity());
                entityList.add(temp);
                tierMapList.add(new HashMap<>());
                tier.putOpt("entityList",entityList);
            }

            //最后更新
            tier.putOpt("entityList",entityList);
            project.putOpt("tierList",tierList);
        }


        return  project;
    }

}
